package org.hxyjs.service.impl;


import org.hxyjs.dao.SchoolDao;
import org.hxyjs.dto.DTO;
import org.hxyjs.dto.MessageEnum;
import org.hxyjs.entity.School;
import org.hxyjs.entity.School;
import org.hxyjs.exception.CustomException;
import org.hxyjs.page.PageInfo;
import org.hxyjs.service.SchoolService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.Random;

@Service("SchoolService")
public class SchoolServiceImpl implements SchoolService {
    @Resource
    SchoolDao schoolDao;
    @Override
    public DTO<School> getAllSchools()  throws Exception{
        List<School> schools = schoolDao.getAllSchools();
        MessageEnum messageEnum  = Optional.ofNullable(schools).isPresent()?MessageEnum.GETSCHOOLSUCCESS: MessageEnum.GETSCHOOLFAIL;
        return new DTO<School>(messageEnum.getCode(),messageEnum.getMessage(),schools);
    }

    @Override
    public DTO<School> deleteSchoolBySno(String sno)  throws Exception{
        Integer result = schoolDao.deleteSchoolBySno(sno);
        MessageEnum messageEnum  =result> 0?MessageEnum.DELETESCHOOLSUCCESS:MessageEnum.DELETESCHOOLFAIL;
        return new DTO<School>(messageEnum.getCode(),messageEnum.getMessage());
    }
    @Transactional(rollbackFor = CustomException.class)
    @Override
    public DTO<School> updateSchoolBySno(School school)  throws Exception{
            School school1 = new School();
            school1.setSno(school.getSno());
            school1.setSname(school.getSname());
            Integer result = schoolDao.updateSchoolBySno(school1);
            if(Math.abs(new Random().nextInt()) % 2 == 0){
                throw new CustomException("修改失败");}
            School school2 = new School();
            school2.setSno(school.getSno());
            school2.setSdescribe(school.getSdescribe());
            result = schoolDao.updateSchoolBySno(school2);
            //isPresent表示判断不为空成立则dto为？与：之间的对象
        MessageEnum messageEnum  =result> 0?MessageEnum.UPDATESCHOOLSUCCESS:MessageEnum.UPDATESCHOOLFAIL;
        return new DTO<School>(messageEnum.getCode(),messageEnum.getMessage());
    }

    @Override
    public DTO<School> addSchool(School school) throws Exception {
        Integer result = schoolDao.addSchool(school);
        MessageEnum messageEnum  = result> 0?MessageEnum.ADDSCHOOLSUCCESS:MessageEnum.ADDSCHOOLFAIL;
        return new DTO<School>(messageEnum.getCode(),messageEnum.getMessage());
    }
    @Override
    public DTO<School> getSchoolByPage(PageInfo pageInfo ) throws Exception {
        List<School> schools = schoolDao.getSchoolByPage(pageInfo);
        MessageEnum messageEnum  = Optional.ofNullable(schools).isPresent()?MessageEnum.GETSCHOOLSUCCESS: MessageEnum.GETSCHOOLFAIL;
        return new DTO<School>(messageEnum.getCode(),messageEnum.getMessage(),schools,pageInfo);
    }
}
